package com.fafu.service.Impl;


import com.fafu.dao.mapper.*;
import com.fafu.model.*;
import com.fafu.pojo.ManagerSearchRepair;
import com.fafu.pojo.NoReadPojo;
import com.fafu.pojo.RefusePojo;
import com.fafu.pojo.StudentSearchRepair;
import com.fafu.service.StudentRepairService;
import com.fafu.service.WorkerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import util.Dictionary;
import util.MyMap;

import java.util.*;

import static util.Dictionary.CODE.NOT_KOWN_ERROR;
import static util.Dictionary.CODE.SUCCESS;
import static util.Dictionary.REPAIR.*;

@Service
public class StudentRepairServiceImpl implements StudentRepairService {
    @Autowired
    private StudentrepairMapper studentrepairMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private ImageMapper imageMapper;
    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private WorkerMapper workerMapper;
    @Autowired
    private WorkerService workerService;
    @Transactional
    @Override
    public Map<String,Object> studentRepair(Studentrepair studentRepair, List<Integer> picIdList) {
        Map<String,Object> resultMap = new HashMap<>();
        long currentTime = System.currentTimeMillis();
        /**
         * 查询学生信息：
         * 查询是否有未读的报修消息，有则返回信息提示。xxx正在报修，请稍等
         *                         ，无则继续
         */
        Example studentExample = new Example(Student.class);
        Example.Criteria studentCriteria = studentExample.createCriteria();
        studentCriteria.andEqualTo("studentIden",studentRepair.getStudentid());
        List<Student> studentList = studentMapper.selectByExample(studentExample);
        if(studentList == null || studentList.size()== 0){
            resultMap.clear();
            resultMap.put("code",Dictionary.CODE.IDEN_ERROR);
            resultMap.put("msg","学号输入错误");
            return resultMap;
        }
        Student student = studentList.get(0);
        Map<String,Object> map = new HashMap<>();
        map.put("studentAddr",student.getStudentAddr());
        List<Studentrepair> declareList = studentrepairMapper.selectIsDeclare(map);
        /**
         * 存在，返回存在。。
         */
        if(declareList!= null && declareList.size()>0){
            resultMap.clear();
            resultMap.put("code",Dictionary.REPAIR.PREPARE_REPAIR_IS_DECLARE);
            resultMap.put("data",declareList.get(0));
            return resultMap;
        }
        studentRepair.setArea(student.getArea());
        studentRepair.setState(REPAIR_STATE_NO_READ);
        studentRepair.setAddTime(currentTime);
        /**
         * 插入并获得主键值
         */
        studentrepairMapper.insertAndGetKey(studentRepair);

        /**
         * 图片字段修改
         */
        for(Integer picId:picIdList){
            Image image = imageMapper.selectByPrimaryKey(picId);
            if(image == null)
                continue;
            image.setRepairid(studentRepair.getId());
            image.setTableIden(Dictionary.TABLE.TABLE_STUDENT_REPAIR);
            imageMapper.updateByPrimaryKey(image);
        }
        resultMap.clear();
        resultMap.put("code",Dictionary.REPAIR.PREPARE_REPAIR_SUCCESS);
        resultMap.put("data",studentRepair.getId());
        return resultMap;
    }

    @Override
    public Map<String, Object> searchList(Map<String, Object> paramMap) {
        /**
         * 1. 查询学生，获得学生的学号和宿舍
         * 2. 查询该学生宿舍的报修情况，
         * 3. 确认是否有操作权限  已读不可修改，为自己发送的不可修改
         */
        Long studenId = (Long) paramMap.get("sid");
        ArrayList<Integer> typsList = (ArrayList<Integer>) paramMap.get("type");
        Student student = studentMapper.selectByPrimaryKey(studenId);
        //查询全部列表
        Example sRExample = new Example(Studentrepair.class);
        Example.Criteria criteria = sRExample.createCriteria();
        criteria.andEqualTo("studentAddr",student.getStudentAddr());
        criteria.andIn("state",typsList);
        PageHelper.startPage((Integer)paramMap.get("pageNum"),(Integer)paramMap.get("pageSize"));
        List<Studentrepair> studentrepairList = studentrepairMapper.selectByExample(sRExample);
        PageInfo pageInfo = new PageInfo(studentrepairList);
        List<Studentrepair> studentrepairs = pageInfo.getList();
        //设置权限和一张图片
        List<StudentSearchRepair> ssrl = new ArrayList<>();
        for(Studentrepair record :studentrepairs){
            StudentSearchRepair data = new StudentSearchRepair();
            BeanUtils.copyProperties(record,data);
            //如果是该学生发的报修，并且未读可以有修改权限
            if(data.getStudentid().equals(studenId)&&data.getState().equals(REPAIR_STATE_NO_READ))
                data.setPower(true);

            //查询获得一张图片
            Example imageExample = new Example(Image.class);
            Example.Criteria imageCriteria = imageExample.createCriteria();
            imageCriteria.andEqualTo("repairid",data.getId());
            List<Image> images = imageMapper.selectByExample(imageExample);
            if(images!=null &&images.size()>0)
                data.setPic(images.get(0).getUrl());
            ssrl.add(data);
        }
        return new MyMap().put("data",ssrl).put("count",pageInfo.getTotal()).toMap();
    }

    @Override
    public Map<String, Object> searchListAll(Map<String, Object> paramMap) {
        PageHelper.startPage((Integer) paramMap.get("pageNum"),(Integer) paramMap.get("pageSize"));
        List<Studentrepair> studentrepairs = studentrepairMapper.selectStudentAll(paramMap);
        PageInfo pageInfo = new PageInfo(studentrepairs);
        return new MyMap().put("data",pageInfo.getList()).put("code", Dictionary.CODE.SUCCESS)
                .put("count",pageInfo.getTotal()).toMap();
    }

    /**
     * 管理员未读信息数量
     * @param operationManage 管理员id
     * @return
     */
    @Override
    public NoReadPojo searchNoReadNum(Integer operationManage) {
        /**
         * 查询管理员的area
         */
        NoReadPojo noReadPojo = new NoReadPojo();
        Manager manager = managerMapper.selectByPrimaryKey(operationManage);
        Studentrepair studentrepairRecord = new Studentrepair();
        studentrepairRecord.setState(REPAIR_STATE_NO_READ);
        studentrepairRecord.setArea(manager.getArea());
        noReadPojo.setRepair(studentrepairMapper.selectCount(studentrepairRecord));

        Message message = new Message();
        message.setState(REPAIR_STATE_NO_READ);
        message.setArea(manager.getArea());
        noReadPojo.setOther(messageMapper.selectCount(message));

        return noReadPojo;
    }

    /**
     * 管理员查询未读信息List
     * @param operationManage
     * @param type
     * @return
     */
    @Override
    public Map<String,Object> searchNoReadList(Integer operationManage,Integer type,Integer pageNum,Integer pageSize) {
        /**
         * 查询管理员，分别查询两种
         */
        Manager manager = managerMapper.selectByPrimaryKey(operationManage);
        if(manager == null){
            return null;
        }
        if(type.equals(SEARCH_TYPE_REPAIR))
            return studentRepairNoReadList(manager.getArea(),pageNum,pageSize);
        else if(type.equals(SEARCH_TYPE_OTHER))
            return messageNoReadList(manager.getArea(),pageNum,pageSize);
        else
            return null;
    }

    @Override
    public Map<String, Object> searchItem(Integer itemId, Integer type) {
        Map<String,Object> reMap = new HashMap<>();
        switch(type){
            case SEARCH_TYPE_REPAIR:
                reMap.put("code",SUCCESS);
                reMap.put("data",studentRepairItem(itemId));break;
            case SEARCH_TYPE_OTHER:
                reMap.put("code",SUCCESS);
                reMap.put("data",messageMapper.selectByPrimaryKey(itemId));break;
            default:
                reMap.put("code",NOT_KOWN_ERROR);
                reMap.put("data",null);
        }
        return reMap;
    }

    @Override
    public Map<String, Object> searchROHItem(Integer itemId, Integer type){
        MyMap paramMap = new MyMap().put("itemId",itemId).put("type",type);
        List<ManagerSearchRepair> reList = studentrepairMapper.searchROHItem(paramMap.toMap());
        Example example = new Example(Image.class);
        example.and().andEqualTo("repairid",itemId);
        List<Image> imageList = imageMapper.selectByExample(example);
        List<String> picList = new ArrayList<>();
        if(imageList != null && imageList.size() > 0)
            for(Image image:imageList)
                picList.add(image.getUrl());
        reList.get(0).setPic(picList);
        return new MyMap().put("data",reList).toMap();
    }

    @Override
    public Map<String, Object> searchRefuseList(Map<String, Object> paramMap) {
        Integer operationId = (Integer) paramMap.get("operationId");
        Manager manager = managerMapper.selectByPrimaryKey(operationId);
        Integer area = manager.getArea();
        paramMap.put("area",area);
        PageHelper.startPage((Integer)paramMap.get("pageNum"),(Integer) paramMap.get("pageSize"));
        List<RefusePojo> refusePojos = studentrepairMapper.searchRefuseList(paramMap);
        PageInfo pageInfo = new PageInfo(refusePojos);
        return new MyMap().put("data",pageInfo.getList()).put("count",pageInfo.getTotal()).toMap();
    }

    @Override
    public Map<String, Object> searchRefuseItem(Map<String, Object> paramMap) {
        RefusePojo refusePojo = studentrepairMapper.searchById(paramMap);
        Integer rid = refusePojo.getId();
        Example example = new Example(Image.class);
        example.and().andEqualTo("repairid",rid);
        List<Image> imgs = imageMapper.selectByExample(example);
        List<String> pic = new ArrayList<>();
        for(Image image:imgs)
            pic.add(image.getUrl());
        refusePojo.setPic(pic);
        List<Worker> workers =workerService.searchWorkerList(new MyMap().put("key","").toMap());
        refusePojo.setWorkerList(workers);
        return new MyMap().put("data",refusePojo).toMap();
    }

    @Override
    public Map<String, Object> repairEnd(Map<String, Object> paramMap) {
        Studentrepair studentrepair = studentrepairMapper.selectByPrimaryKey(paramMap.get("itemId"));
        studentrepair.setState(0);
        studentrepairMapper.updateByPrimaryKeySelective(studentrepair);
        return new MyMap().put("code",SUCCESS).put("data","success").toMap();
    }

    @Override
    public Map<String, Object> repairOtherEnd(Map<String, Object> paramMap) {
        Message message = messageMapper.selectByPrimaryKey(paramMap.get("itemId"));
        message.setState(0);
        messageMapper.updateByPrimaryKeySelective(message);
        return new MyMap().put("code",SUCCESS).put("data","success").toMap();
    }

    private Map<String,Object> studentRepairNoReadList(Integer area,Integer pageNum,Integer pageSize){
        Example studentExample = new Example(Studentrepair.class);
        Example.Criteria studentCriteria = studentExample.createCriteria();
//        //设置为未处理
        studentCriteria
                .andEqualTo("state",REPAIR_STATE_NO_READ);
        Studentrepair studentrepair = new Studentrepair();
        studentrepair.setState(REPAIR_STATE_READ);
        studentrepair.setArea(area);
        MyMap record = new MyMap();
//        studentrepairMapper.updateToRead(record.put("area",area).toMap());
        studentrepairMapper.updateByExampleSelective(studentrepair,studentExample);
        //查询已读，表示未处理
        studentExample.clear();
        studentCriteria = studentExample.createCriteria();
        studentCriteria.andEqualTo("state",REPAIR_STATE_READ)
                .andEqualTo("area",area);
        PageHelper.startPage(pageNum,pageSize);
        List<Studentrepair> relist = studentrepairMapper.selectByExample(studentExample);
        PageInfo pageInfo = new PageInfo(relist);
        return new MyMap().put("data",pageInfo.getList()).put("count",pageInfo.getTotal()).toMap();
    }
    private Map<String,Object> messageNoReadList(Integer area,Integer pageNum,Integer pageSize){
        Example messageExample = new Example(Message.class);
        Example.Criteria messageCriteria = messageExample.createCriteria();
        //设置字段为未处理
        messageCriteria.andEqualTo("area",area)
                .andEqualTo("state",REPAIR_STATE_NO_READ);
        Message message = new Message();
        message.setState(REPAIR_STATE_READ);
        messageMapper.updateByExampleSelective(message,messageExample);
        //查询
        messageExample.clear();
        messageCriteria = messageExample.createCriteria();
        messageCriteria.andEqualTo("area",area)
                .andEqualTo("state",REPAIR_STATE_READ);
        PageHelper.startPage(pageNum,pageSize);
        List list = messageMapper.selectByExample(messageExample);
        PageInfo pageInfo = new PageInfo(list);
        return  new MyMap().put("data",pageInfo.getList()).put("count",pageInfo.getTotal()).toMap();
    }
    private ManagerSearchRepair studentRepairItem(Integer itemId){
        Studentrepair studentrepair= studentrepairMapper.selectByPrimaryKey(itemId);
        ManagerSearchRepair reData = new ManagerSearchRepair();
        BeanUtils.copyProperties(studentrepair,reData);
        //查询学生信息
        Example studentExample = new Example(Student.class);
        Example.Criteria studentCriteria = studentExample.createCriteria();
        studentCriteria.andEqualTo("studentIden",studentrepair.getStudentid());
        Student student = studentMapper.selectByExample(studentExample).get(0);
        reData.setName(student.getStudengName());
        reData.setGender(student.getGender());
        //查询图片
        Example imageExample = new Example(Image.class);
        Example.Criteria imageCriteria = imageExample.createCriteria();
        imageCriteria.andEqualTo("repairid",itemId).andEqualTo("tableIden",Dictionary.TABLE.TABLE_STUDENT_REPAIR);
        List<Image> imageList = imageMapper.selectByExample(imageExample);
        List<String> pic = new ArrayList<>();
        for(Image re: imageList){
            pic.add(re.getUrl());
        }
        reData.setPic(pic);
        return reData;

    }

}
